import 'dart:io';

import 'package:bai_le_men_im/conversation/inputPanel/audio.dart';
import 'package:flutter/material.dart';
import 'package:overlay_support/overlay_support.dart';
import '../../conversation/inputPanel/emoji.dart';
import '../../constants.dart' show emojis;

import '../../constants.dart' show AppColors, AppStyles, Constants;
import 'package:permission_handler/permission_handler.dart';
import 'package:image_picker/image_picker.dart';

enum InputType { text, voice, emoji, plus }

class InputPanel extends StatefulWidget {
  final Function onSendMsgHandler;
  InputPanel({this.onSendMsgHandler});
  @override
  _InputPanelState createState() => _InputPanelState();
}

class _InputPanelState extends State<InputPanel> {
  InputType _type = InputType.text;

  final maxChatBoxLinesForDisplay = 4;
  TextEditingController _controller = TextEditingController();
  FocusNode _inputTextFieldNode = FocusNode();

  String _lastInputText = '';
  int _lastBaseOffset;
  int _lastExtentOffset;

  bool _skipNext1 = false;
  bool _skipNext2 = false;

  bool _showSendBtn = false;

  Future getImage(String sourceStr) async {
    try {
      ImageSource source;
      switch (sourceStr) {
        case 'storage':
          source = ImageSource.gallery;
          break;
        default:
          source = ImageSource.camera;
          break;
      }
      File _image = await ImagePicker.pickImage(source: source);
      if (_image == null) {
      } else {
        // print(_image.path);
        widget.onSendMsgHandler(_image.path, 'image');
      }
    } catch (e) {
      print('imagePicker error');
    }

    // setState(() {
    //   _image = image;
    // });
  }

  @override
  void initState() {
    _inputTextFieldNode.addListener(() {
      print(_inputTextFieldNode);
      print('_inputTextFieldNode addListener');
      // if (_inputTextFieldNode.hasFocus) {
      //   FocusScope.of(context).requestFocus(_inputTextFieldNode);
      // } else {
      //   FocusScope.of(context).requestFocus(FocusNode());
      // }
    });
    _controller.addListener(() {
      this.setState(() {
        String words = _controller.text.trim();
        if (words.isEmpty) {
          _showSendBtn = false;
        } else {
          _showSendBtn = true;
        }
      });
      return;
      if (_type == InputType.emoji) {
        FocusScope.of(context).requestFocus(FocusNode());
      }
      if (_skipNext1) {
        _skipNext1 = false;
        _skipNext2 = true;
        return;
      }
      if (_skipNext2) {
        _skipNext2 = false;
        return;
      }
      String _newValue = _controller.text;
      if (_controller.text.length < _lastInputText.length) {
        // 如果新值的长度小于旧值的长度，正在进行删除
        if (_lastBaseOffset == _lastExtentOffset && _lastBaseOffset > -1) {
          // 如果删除的是单个文字，则找出被删除的文字，进行判断
          final int baseOffset = _controller.selection.baseOffset;
          final int extentOffset = _controller.selection.extentOffset;

          // 找到删除的是什么字符
          // 光标左侧的文字
          String _strBefSection = _lastInputText.substring(0, _lastBaseOffset);
          // 光标右侧的文字
          String _strAftSection = _lastInputText.substring(_lastBaseOffset);
          bool _isEmoji = false; // 是否是表情，默认不是表情
          if (_strBefSection.endsWith(']') && _strBefSection.length > 2) {
            // 且光标左侧的文字中包含有"["符号
            int _iLastLeftStartSingle = _strBefSection.lastIndexOf('[');
            if (_iLastLeftStartSingle > -1) {
              // 找到两个[]符号中间的文字，与emojis数组做比对，如果emojis数组中有一样的元素，则认为要删除的东西是一个表情
              String _word = _strBefSection.substring(
                  _iLastLeftStartSingle + 1, _strBefSection.length - 1);
              if (emojis.any((emoji) {
                return _word == emoji;
              })) {
                _isEmoji = true;
                _newValue = _strBefSection.substring(0, _iLastLeftStartSingle) +
                    _strAftSection;
                print('1_controller.text = ${_controller.text}');
                print('1_newValue = ${_newValue}');

                _lastInputText = _newValue;
                _lastBaseOffset = _controller.selection.baseOffset;
                _lastExtentOffset = _controller.selection.extentOffset;

                _skipNext1 = true;

                _controller.text = _newValue;
                _controller.selection = TextSelection.fromPosition(
                    TextPosition(offset: _iLastLeftStartSingle));
                // _controller.selection = TextSelection.fromPosition(
                //     TextPosition(offset: _controller.text.length));
                // _controller.selection = TextSelection(
                //     baseOffset: _iLastLeftStartSingle - 1,
                //     extentOffset: _iLastLeftStartSingle - 1);

                return;
              }
            }
          }
        }
      }
      _lastInputText = _newValue;
      _lastBaseOffset = _controller.selection.baseOffset;
      _lastExtentOffset = _controller.selection.extentOffset;
      // _controller.text = _newValue;
      //  _controller.selection = TextSelection(
      //               baseOffset: _lastBaseOffset,
      //               extentOffset: _lastExtentOffset);
      // _controller = TextEditingController.fromValue(TextEditingValue(text: _newValue,
      //   selection: TextSelection.fromPosition(TextPosition(
      //     offset: 3
      //   ))
      // ));
    });
    super.initState();
  }

  @override
  void dispose() {
    try {
      _inputTextFieldNode.unfocus();
    } catch (e) {}
    _controller.dispose();
    super.dispose();
  }

  @override
  void didChangeDependencies() {
    print('didChangeDependencies');
    print('_type = ${_type}');
    super.didChangeDependencies();
  }

  @override
  void didUpdateWidget(InputPanel oldWidget) {
    // TODO: implement didUpdateWidget

    print('didUpdateWidget');
    super.didUpdateWidget(oldWidget);
  }

  _onSubmitHandler(String text) async {
    try {
      _controller.text = '';
      await widget.onSendMsgHandler(text, 'text');
    } catch (e) {
      // TODO: 发送失败
      print(e);
      print('发送失败');
    }
  }

  inputEmojiHandler(InputTypeEmoji emoji) {
    print(emoji.content);
    TextSelection _selection = _controller.selection;
    int _start =
        _selection.start > -1 ? _selection.start : _controller.text.length;
    int _end = _selection.end;
    // 光标左侧的文字
    String _strBefSection = _controller.text.substring(0, _start);
    // 光标右侧的文字
    String _strAftSection = _controller.text.substring(_start);
    if (emoji.content == 'delete') {
      if (_start <= 0) return;
      bool _isSingleChar = true;
      if (_start != _end) {
        _isSingleChar = false;
      }
      if (_isSingleChar) {
        bool _isEmoji = false; // 是否是表情，默认不是表情
        // 如果光标左侧的文字以“]”结尾, 且长度大于2
        // if (_strBefSection.endsWith(']') && _strBefSection.length > 2) {
        //   // 且光标左侧的文字中包含有"["符号
        //   int _iLastLeftStartSingle = _strBefSection.lastIndexOf('[');
        //   if (_iLastLeftStartSingle > -1) {
        //     // 找到两个[]符号中间的文字，与emojis数组做比对，如果emojis数组中有一样��元素，则认为要删除的东西是一个表情
        //     String _word = _strBefSection.substring(
        //         _iLastLeftStartSingle + 1, _strBefSection.length - 1);
        //     if (emojis.any((emoji) {
        //       return _word == emoji;
        //     })) {
        //       _isEmoji = true;
        //       _controller.text =
        //           _strBefSection.substring(0, _iLastLeftStartSingle) +
        //               _strAftSection;
        //       print(_controller.text);
        //       _controller.selection = TextSelection.fromPosition(
        //           TextPosition(offset: _controller.text.length));
        //       // _controller.selection = TextSelection(
        //       //     baseOffset: _iLastLeftStartSingle - 1,
        //       //     extentOffset: _iLastLeftStartSingle - 1);
        //     }
        //   }
        // }
        if (!_isEmoji) {
          // 普通文字
          // _controller.selection =
          //     TextSelection(baseOffset: _start - 2, extentOffset: _start - 2);

          _controller.text =
              _strBefSection.substring(0, _start - 1) + _strAftSection;
          _controller.selection =
              TextSelection.fromPosition(TextPosition(offset: _start - 1));
        }
      }
    } else {
      final String _str = _strBefSection + '[${emoji.content}]';
      final String _newValue = _str + _strAftSection;
      _controller.text = _str + _strAftSection;
      _controller.selection = TextSelection.fromPosition(
          TextPosition(offset: _str.length, affinity: TextAffinity.upstream));

      // _lastInputText = _newValue;
      // _lastBaseOffset = _str.length;
      // _lastExtentOffset = _str.length;
      // _controller.selection = TextSelection(
      //     baseOffset: _controller.text.length,
      //     extentOffset: _controller.text.length);
    }
  }

  @override
  Widget build(BuildContext context) {
    final paddingH = 16.0;
    final paddingV = 12.0;
    final chatBoxRadius = 4.0;

    var firstFontContent = 0xe7e2; // 语音切换
    if (_type == InputType.voice) {
      firstFontContent = 0xe7db; // 键盘图标
    }
    var emojiBtnContent = 0xe60c;
    if (_type == InputType.emoji) {
      emojiBtnContent = 0xe7db; // 键盘图标
    }
    return Column(
      children: <Widget>[
        Container(
          padding:
              EdgeInsets.symmetric(horizontal: paddingH, vertical: paddingV),
          decoration: BoxDecoration(
              color: const Color(AppColors.ChatBoxBg),
              border: Border(
                  top: BorderSide(
                      color: const Color(AppColors.DividerColor),
                      width: Constants.DividerWidth))),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.end,
            children: <Widget>[
              IconButton(
                  onPressed: () async {
                    if (_type == InputType.voice) {
                      this.setState(() {
                        _type = InputType.text;
                      });
                      return;
                    } else {
                      Map<PermissionGroup, PermissionStatus> permissions =
                          await PermissionHandler().requestPermissions([
                        PermissionGroup.microphone,
                        PermissionGroup.storage
                      ]);
                      List _permissions =
                          List.generate(permissions.keys.length, (i) {
                        return permissions[permissions.keys.toList()[i]] ==
                            PermissionStatus.granted;
                      });
                      if (_permissions.every((_permission) {
                        return _permission;
                      })) {
                        this.setState(() {
                          _type = InputType.voice;
                        });
                        return;
                      } else {
                        toast('获取麦克风权限失败');
                      }
                    }
                  },
                  icon: Icon(
                      IconData(
                        firstFontContent,
                        fontFamily: Constants.IconFontFamily,
                      ),
                      size: Constants.ActionIconSizeLarge,
                      color: const Color(AppColors.ActionIconColor))),
              Expanded(
                child: Container(
                  margin: const EdgeInsets.only(left: 4.0, right: 4.0),
                  decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(chatBoxRadius)),
                  child: _type == InputType.voice
                      ? InputAudioBtn(onSendAudioMsg: (Map payload) {
                          widget.onSendMsgHandler(payload, 'audio');
                        })
                      : LayoutBuilder(
                          builder: (context, size) {
                            // 计算当前的文本需要占用的行数
                            TextSpan _text = TextSpan(
                                text: _controller.text,
                                style: AppStyles.ChatBoxTextStyle);

                            TextPainter _tp = TextPainter(
                                text: _text,
                                textDirection: TextDirection.ltr,
                                textAlign: TextAlign.left);
                            _tp.layout(maxWidth: size.maxWidth);

                            final _lines =
                                (_tp.size.height / _tp.preferredLineHeight)
                                    .ceil();

                            return TextField(
                              onSubmitted: _onSubmitHandler,
                              focusNode: _inputTextFieldNode,
                              autofocus: _controller.text.length > 0,
                              textInputAction: TextInputAction.send,
                              decoration: InputDecoration(
                                  border: InputBorder.none,
                                  contentPadding: const EdgeInsets.all(10.0)),
                              controller: _controller,
                              cursorColor:
                                  const Color(AppColors.ChatBoxCursorColor),
                              maxLines: _lines < maxChatBoxLinesForDisplay
                                  ? null
                                  : maxChatBoxLinesForDisplay,
                              style: AppStyles.ChatBoxTextStyle,
                            );
                          },
                        ),
                ),
              ),
              _showSendBtn
                  ? (MaterialButton(
                      minWidth: 20.0,
                      // height: 10.0,
                      padding: EdgeInsets.symmetric(
                          horizontal: 15.0, vertical: 10.0),
                      onPressed: () {
                        String text = _controller.text.trim();
                        _controller.clear();
                        widget.onSendMsgHandler(text, 'text');
                      },
                      color: Colors.blueAccent,
                      textColor: Colors.white,
                      child: Text('发送'),
                    ))
                  : (IconButton(
                      onPressed: () {
                        print('显示更多功能');
                        if (_type == InputType.plus) {
                          this.setState(() {
                            _type = InputType.text;
                          });

                          FocusScope.of(context)
                              .requestFocus(_inputTextFieldNode);
                          return;
                        }
                        this.setState(() {
                          _type = InputType.plus;
                        });

                        FocusScope.of(context).requestFocus(FocusNode());
                      },
                      icon: Icon(
                          IconData(
                            0xe616,
                            fontFamily: Constants.IconFontFamily,
                          ),
                          size: Constants.ActionIconSizeLarge,
                          color: const Color(AppColors.ActionIconColor))))
              /*
              IconButton(
                  onPressed: () {
                    print('表情包');
                    if (_type == InputType.text) {
                      _type = InputType.emoji;
                      FocusScope.of(context).requestFocus(FocusNode());
                    } else {
                      _type = InputType.text;

                      FocusScope.of(context).requestFocus(_inputTextFieldNode);
                    }
                    this.setState(() {});
                  },
                  icon: Icon(
                      IconData(
                        emojiBtnContent,
                        fontFamily: Constants.IconFontFamily,
                      ),
                      size: Constants.ActionIconSizeLarge,
                      color: const Color(AppColors.ActionIconColor))),
              IconButton(
                  onPressed: () {
                    print('显示更多功能');
                  },
                  icon: Icon(
                      IconData(
                        0xe616,
                        fontFamily: Constants.IconFontFamily,
                      ),
                      size: Constants.ActionIconSizeLarge,
                      color: const Color(AppColors.ActionIconColor)))
                      */
            ],
          ),
        ),
        renderPlusInput(),
        SingleChildScrollView(
          child: _type == InputType.emoji
              ? Container(
                  height: 230.0,
                  child: InputEmojis(
                    onTap: inputEmojiHandler,
                  ),
                )
              : Container(),
        )
      ],
    );
  }

  Widget renderPlusInput() {
    if (_type == InputType.plus) {
      return Container(
        padding: EdgeInsets.all(20.0),
        decoration: BoxDecoration(
          color: Colors.grey[200],
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            BtnPlus(
              onPressed: () async {
                Map<PermissionGroup, PermissionStatus> permissions =
                    await PermissionHandler().requestPermissions(
                        [PermissionGroup.photos, PermissionGroup.storage]);
                print(permissions);
                await getImage('storage');
              },
              iconData: Icons.photo,
              title: '照片',
            ),
            BtnPlus(
              onPressed: () async {
                Map<PermissionGroup, PermissionStatus> permissions =
                    await PermissionHandler().requestPermissions(
                        [PermissionGroup.photos, PermissionGroup.storage]);
                print(permissions);
                await getImage('photos');
              },
              iconData: Icons.photo_camera,
              title: '拍摄',
            ),
            BtnPlus(
              onPressed: () async {
                widget.onSendMsgHandler(null, 'RedEnvelope');
              },
              iconData: Icons.redeem,
              title: '红包',
            ),
          ],
        ),
      );
    }
    return Container();
  }
}

class BtnPlus extends StatelessWidget {
  final Function onPressed;
  final IconData iconData;
  final String title;
  BtnPlus({this.onPressed, this.iconData, this.title});
  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
          // color: Colors.white,
          // borderRadius: BorderRadius.circular(8.0)
          ),
      padding: EdgeInsets.all(5.0),
      child: InkWell(
        onTap: this.onPressed,
        child: Column(
          children: <Widget>[
            Container(
                decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(8.0)),
                padding: EdgeInsets.all(15.0),
                margin: EdgeInsets.symmetric(horizontal: 8.0),
                child: Icon(
                  iconData,
                  color: Colors.grey[800],
                  size: 35.0,
                )),
            SizedBox(
              height: 5.0,
            ),
            Text(title,
                style: TextStyle(color: Colors.grey[600], fontSize: 13.0))
          ],
        ),
      ),
    );
    return Container(
      child: IconButton(
        padding: EdgeInsets.all(0.0),
        icon: Icon(
          iconData,
          color: Colors.grey,
          size: 40.0,
        ),
        onPressed: onPressed,
      ),
    );
  }
}
